<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021-04-28
 * Time: 14:26
 */
namespace app\admin\controller\system;
use app\admin\controller\command\AdminController;
use app\admin\controller\command\ControllerAnnotation;
use app\admin\controller\command\NodeAnotation;
use app\admin\model\system\SystemModel;
use app\admin\model\traits\Curd;
use app\admin\model\traits\ModelHandle;
use app\admin\model\traits\TablHandle;
use think\facade\Db;
use think\Request;
use think\App;

/**
 * @ControllerAnnotation(title="模型管理")
 * Class Auth
 * @package app\admin\controller\system
 */
class Models extends AdminController
{
    use Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SystemModel();
        $array = TablHandle::getClassName(__CLASS__);
        $str = $array[(count($array)-1>=0?count($array)-1:0)];
        if(is_file(__DIR__.DS.'field'.DS.$str.'.txt')){
            $arr = file_get_contents(__DIR__.DS.'field'.DS.$str.'.txt');
            $this->AllData = json_decode($arr,true);
        }else{
            $this->AllData = [
                'field'=>[]
            ];
        }
    }
    /**
     * @NodeAnotation(title="更新表")
     */
    public function updatetable(Request $request){
        $data = $request->param();
        $mysql = getDataBaseConfig('database');
        $qianzui = getDataBaseConfig('prefix');
        $sql = "select TABLE_NAME  AS 'table',TABLE_COMMENT as 'name',engine as 'engine' from information_schema.tables where table_schema='".$mysql."'";
        $array = Db::query($sql);
        foreach ($array as $k=>$value){
            $table = $value['table'];
            $tables = str_replace($qianzui,'',$table);
            $models = Db::name('system_model')
                ->where('table',$tables)
                ->findOrEmpty();
            if(empty($models)){
                $data = [
                    'name'=>$value['name'],
                    'table'=>$tables,
                    'engine'=>$value['engine'],
                    'prefix'=>$qianzui,
                    'create_time'=>time(),
                    'update_time'=>time(),
                ];
                $data['id'] = Db::name('system_model')
                    ->insertGetId($data);
                $newsql = 'show full fields from '.$table;
                $newarray = Db::query($newsql);
                $newarray = TablHandle::CommentToTabl($newarray,$tables);
                foreach ($newarray as $key=>$va){
                    $field = Db::name('system_field')
                        ->where('table',$tables)
                        ->where('field',$va['field'])
                        ->findOrEmpty();
                    if($va['field']=='create_time'||$va['field']=='update_time'||$va['field']=='status'){
                        $va['sort'] = 10;
                        if($va['field']=='status'||$va['field']=='create_time'){
                            $va['show'] = 1;
                            if($va['field']=='status'){
                                $va['edit'] = 1;
                            }
                        }
                    }
                    if($va['field']=='delete_time'){
                        $va['sort'] = 0;
                    }
                    if($va['field']=='id'){
                        $va['sort'] = 9999;
                        $va['show'] = 1;
                    }
                    if($va['field']=='name'){
                        $va['sort'] = 9000;
                    }
                    if(empty($field)){
                        $va['create_time'] = time();
                        $va['update_time'] = time();
                        Db::name('system_field')
                            ->insert($va);
                    }else{
                        $va['update_time'] = time();
                        Db::name('system_field')
                            ->where('id',$field['id'])
                            ->update($va);
                    }
                    $newarray[$key] = $va;
                }
                $value['model'] = $newarray;
            }else{
                $newarray = [];
                $newarray['engine'] = $value['engine'];
                $newarray['name'] = $value['name'];
                $newarray['update_time'] = time();
//                echo '<pre>';
//                print_r($models);
//                print_r($newarray);
//                exit;
                Db::name('system_model')
                    ->where('id',$models['id'])
                    ->update($newarray);
                $newsql = 'show full fields from '.$table;
                $newarray = Db::query($newsql);
//                echo '<pre>';
//                print_r($newarray);
//                exit;
                $newarray = TablHandle::CommentToTabl($newarray,$tables);
                foreach ($newarray as $key=>$va){
                    $field = Db::name('system_field')
                        ->where('table',$tables)
                        ->where('field',$va['field'])
                        ->findOrEmpty();
                    if(empty($field)){
                        $va['create_time'] = time();
                        $va['update_time'] = time();
                        Db::name('system_field')
                            ->insert($va);
                    }else{
                        $va['update_time'] = time();
                        Db::name('system_field')
                            ->where('id',$field['id'])
                            ->update($va);
                    }
                    $newarray[$key] = $va;
                }
                $value['model'] = $newarray;
            }
            $array[$k] = $value;
        }
        return $this->success('更新成功');
    }
    public function clineartable(Request $request){
        $id = $request->param('id',null);
        if(empty($id)){
            return $this->error('清空失败');
        }
        $model = Db::name('system_model')
            ->where('id',$id)
            ->findOrEmpty();
        $table = $model['prefix'].$model['table'];
        $sql = "truncate table `$table`";
        try{
            Db::query($sql);
        }catch (\Exception $e){
            return $this->error('清空失败');
        }
        return $this->success('清空成功');
    }
    /**
     * @NodeAnotation(title="添加")
     */
    public function add(Request $request)
    {
        $field = $this->AllData['field'];
//        echo '<pre>';
//        print_r($field);
//        exit;
        if($request->isAjax()){
            $data = $this->SubmitDataArray();
            if(!(isset($data['create_time'])&&$data['create_time'])){
                $data['create_time'] = time();
            }
            if(!(isset($data['update_time'])&&$data['update_time'])){
                $data['update_time'] = time();
            }
            if(empty($data['prefix'])){
                $data['prefix'] = getDataBaseConfig('prefix');
            }
//            return $this->error('失败',201,$data);
            $bool = ModelHandle::createTable($data);
            if(!$bool){
                return $this->error('添加失败');
            }
            $shuju = $this->model->where('table',$data['table'])
                ->findOrEmpty()->toArray();
            $this->model->where('id',$shuju['id'])->save(['tabletype'=>$data['tabletype'],'is_page'=>$data['is_page'],'update_time'=>time()]);
            if(!$bool){
                return $this->error('添加失败');
            }else{
                return $this->success('添加成功');
            }
        }
        $data = $this->arrangementData();
        $this->assign('data',$data);
        $this->assign('field',$field);
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit(Request $request)
    {
        $field = $this->AllData['field'];
        if($request->isAjax()){
            $data = $this->SubmitDataArray();
            if(empty($data['id'])){
                return $this->error('请输入要修改的id');
            }
            if(!(isset($data['update_time'])&&$data['update_time'])){
                $data['update_time'] = time();
            }
            $data['prefix'] = getDataBaseConfig('prefix');
            $shuju = $this->model->where('id',$data['id'])
                ->findOrEmpty()->toArray();
            $bool = ModelHandle::updateTable($shuju,$data);
            if(!$bool){
                return $this->error('更新失败');
            }
            $mo = $this->model->find($data['id']);
            $bool = $mo->save($data);
            if($bool){
                return $this->success('更新成功');
            }else{
                return $this->error('更新失败');
            }
        }
        $tiaojian = $request->param();
        $data = $this->model->find($tiaojian['id'])->toArray();
        foreach ($tiaojian as $key=>$value){
            $data[$key] = $value;
        }
        $this->assign('data',$data);
        $this->assign('field',$field);
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="删除")
     */
    public function delete(Request $request)
    {
        $data = $request->param();
        $bool = ModelHandle::deleteTable($data['id']);
        if(!$bool){
            return $this->error('删除失败');
        }
        $bool = $this->model->destroy($data['id']);
        if($bool){
            return $this->success('删除成功',$data);
        }else{
            return $this->error('删除失败');
        }
    }

    public function ces(){
        $data = [
            'id'=>'53',
            'name'=>'测试表1',
            'table'=>'my_cess',
//            'engine'=>'InnoDB',
            'engine'=>'InnoDB',
            'tabletype'=>'ordinary',
            'prefix'=>'ea_',
            'is_page'=>1,
        ];
        $shuju = $this->model->where('id',53)
            ->findOrEmpty()->toArray();
        $bool = ModelHandle::updateTable($shuju,$data);
        var_dump($bool);

    }
}